<template>
	<view class="page-container">
		<!-- 顶部导航栏 - 使用指定组件 -->
		<u-navbar bgColor="#F5F9FC" :placeholder="true" :border="true" height="48px">
			<view slot="left" class="navbar-left">
				<navigator url="/pages/index/index" open-type="switchTab" class="back-button">
					<view class="nav-back-content">
						<u-icon color="#1e88e5" name="arrow-left" size="20"></u-icon>
						<text class="nav-title">工资管理</text>
					</view>
				</navigator>
			</view>
		</u-navbar>

		<!-- 年份选择器 -->
		<view class="year-picker-container">
			<picker mode="selector" :range="yearRange" :value="yearIndex" @change="handleYearChange"
				class="year-picker">
				<view class="year-display selected" style="display: flex;">
					<view>{{ yearRange[yearIndex] }}</view>
					<view style="margin-left: 10rpx;">
						<u-icon color="#ffffff" name="list-dot" size="22"></u-icon>
					</view>
				</view>
			</picker>
		</view>

		<!-- 月份滑动区域 -->
		<scroll-view class="month-slider" scroll-x="true" :scroll-left="scrollInto">
			<view v-for="(month, index) in monthRange" :key="month.value" class="month-tab"
				:class="{ 'month-tab-selected': selectedMonthIndex === index }" @click="selectMonth(index)">
				{{ month.text }}
			</view>
		</scroll-view>

		<!-- 加载状态 -->
		<view v-if="isLoading" class="loading-container">
			<u-loading-icon size="30" color="#1677ff"></u-loading-icon>
			<view class="loading-text">加载中...</view>
		</view>

		<!-- 核心统计卡片 -->
		<view class="stat-card" v-if="!isLoading">
			<view class="stat-item">
				<text class="stat-label">应发工资</text>
				<text class="stat-value">{{ totalPayableSalary.toFixed(2) }}</text>
			</view>
			<view class="stat-item">
				<text class="stat-label">应交税</text>
				<text class="stat-value">{{ totalIncomeTax.toFixed(2) }}</text>
			</view>
			<view class="stat-item">
				<text class="stat-label">员工人数</text>
				<text class="stat-value">{{ totalEmployeeCount }}</text>
				<view class="staff-status-container">
					<text class="staff-status">在职 {{ activeEmployeeCount }}</text>
					<text class="staff-status staff-status-gray">离职 {{ inactiveEmployeeCount }}</text>
				</view>
			</view>
			<view class="employee-manage-btn" @click="gotoEmployeeManage">员工工资管理</view>
		</view>

		<!-- 配置按钮区域 -->
		<view class="config-buttons" v-if="!isLoading">
			<view class="config-btn" @click="tofield('/pageNew/salary/Companysalary')">公司配置</view>
			<view class="config-btn" @click="tofield('/pageNew/salary/salaryFields')">自动定义配置</view>
			<view class="config-btn active-btn">最低档 {{ cityName }}</view>
		</view>

		<!-- 社保医保公积金模块 -->
		<view class="insure-container" v-if="!isLoading">
			<view class="insure-item">
				<text class="insure-title">社保缴纳</text>
				<text class="insure-value">{{ totalSocialSecurity.toFixed(2) }}</text>
			</view>
			<view class="insure-item">
				<text class="insure-title">医保缴纳</text>
				<text class="insure-value">{{ totalMedicalInsurance.toFixed(2) }}</text>
			</view>
			<view class="insure-item">
				<text class="insure-title">公积金缴纳</text>
				<text class="insure-value">{{ totalHousingFund.toFixed(2) }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 年份选择相关
				yearRange: [],
				yearIndex: 0,
				selectedYear: '',

				// 月份选择相关
				monthRange: [],
				selectedMonthIndex: 0,
				scrollInto: 0,
				screenWidth: uni.getSystemInfoSync().screenWidth * 2,
				monthWidth: 170,
				isFirstLoad: true,

				currentYear: new Date().getFullYear(),
				currentMonth: new Date().getMonth() + 1,

				// 数据相关
				isLoading: false,
				companyInfo: uni.getStorageSync('companyInfo'),
				http: uni.$u.http,
				employees: [],
				salaryItems: [],
				salaryItemMap: {},

				// 统计数据
				totalPayableSalary: 0,
				totalIncomeTax: 0,
				totalEmployeeCount: 0,
				activeEmployeeCount: 0, // 在职人数（isOnJob=1）
				inactiveEmployeeCount: 0, // 离职人数（isOnJob=0）
				totalSocialSecurity: 0,
				totalMedicalInsurance: 0,
				totalHousingFund: 0,
				cityName: '杭州',

				// 工资项ID映射（与员工工资管理页面保持一致）
				deductionItemIds: {
					pension: "4", // 养老保险（个人）
					medical: "5", // 医疗保险（个人）
					housingFund: "7", // 住房公积金（个人）
					unemployment: "1990994050818953218", // 失业保险（个人）
					incomeTax: "8" // 个人所得税
				}
			};
		},
		computed: {
			companyId() {
				return this.companyInfo.id || '1986303016356728834';
			}
		},
		onLoad() {
			// 初始化年份数据
			this.initYearRange();
			// 初始化月份数据
			this.initMonthRange();
			// 首次加载时计算滚动位置
			this.calculateScrollPosition();
			// 标记为非首次加载
			this.isFirstLoad = false;

			// 加载工资项配置
			this.loadSalaryItems().then(() => {
				// 加载统计数据
				this.loadStatisticsData();
			});
		},
		methods: {
			tofield(e) {
				uni.navigateTo({
					url: e
				})
			},

			// 初始化年份范围
			initYearRange() {
				const currentYear = new Date().getFullYear();
				this.yearRange = [];

				// 生成近5年
				for (let i = currentYear; i >= currentYear - 4; i--) {
					this.yearRange.push(i + '年');
				}

				this.yearIndex = 0;
				this.selectedYear = currentYear.toString();
			},

			// 初始化月份范围
			initMonthRange() {
				this.monthRange = [];

				// 确定最大月份
				const maxMonth = this.selectedYear == this.currentYear ? this.currentMonth : 12;

				// 添加月份数据
				for (let i = 1; i <= maxMonth; i++) {
					this.monthRange.push({
						text: i + '月',
						value: i.toString()
					});
				}

				// 首次加载时设置选中当前月份
				if (this.isFirstLoad) {
					this.selectedMonthIndex = this.currentMonth - 1;
				} else {
					// 非首次加载时，确保选中索引不超出范围
					if (this.selectedMonthIndex >= this.monthRange.length) {
						this.selectedMonthIndex = this.monthRange.length - 1;
					}
				}
			},

			// 年份变更处理
			handleYearChange(e) {
				const prevIndex = this.yearIndex;
				this.yearIndex = e.detail.value;
				// 提取选中的年份数字
				this.selectedYear = this.yearRange[this.yearIndex].replace('年', '');

				// 保存当前选中的月份索引
				const currentSelectedIndex = this.selectedMonthIndex;

				// 重新初始化月份范围
				this.initMonthRange();

				// 恢复之前选中的月份索引
				this.selectedMonthIndex = currentSelectedIndex;

				// 确保索引有效
				if (this.selectedMonthIndex >= this.monthRange.length) {
					this.selectedMonthIndex = this.monthRange.length - 1;
				}

				// 年份改变时重新加载数据
				if (prevIndex !== this.yearIndex) {
					this.loadStatisticsData();
				}
			},

			// 月份选择处理
			selectMonth(index) {
				if (this.selectedMonthIndex !== index) {
					this.selectedMonthIndex = index;
					this.loadStatisticsData();
				}
			},

			// 计算滚动位置
			calculateScrollPosition() {
				const totalMonthWidth = this.monthRange.length * this.monthWidth;
				const screenHalfWidth = this.screenWidth / 2;
				const currentItemOffset = this.selectedMonthIndex * this.monthWidth;

				if (this.monthRange.length <= 1) {
					this.scrollInto = 0;
				} else if (this.selectedMonthIndex === 0) {
					this.scrollInto = 0;
				} else if (this.selectedMonthIndex === this.monthRange.length - 1) {
					this.scrollInto = totalMonthWidth - screenHalfWidth;
				} else {
					this.scrollInto = currentItemOffset - screenHalfWidth;
				}
			},

			// 加载工资项配置
			async loadSalaryItems() {
				try {
					const res = await this.http.get('/VipSalaryItem/list', {
						params: {
							companyId: this.companyId,
							pageSize: 1000
						}
					});

					if (res.code === 200 && res.data?.data) {
						// 处理工资项数据
						this.salaryItems = res.data.data.map((item) => {
							const fieldName = `salaryItem_${item.id}`;
							this.salaryItemMap[item.id] = {
								fieldName,
								isIncome: item.itemType === 1
							};
							return {
								...item,
								itemId: item.id,
								fieldName,
								isIncome: item.itemType === 1
							};
						});
					} else {
						console.warn('加载工资项失败，使用默认配置');
						this.useDefaultSalaryItems();
					}
				} catch (error) {
					console.error('加载工资项配置失败:', error);
					this.useDefaultSalaryItems();
				}
			},

			// 使用默认工资项配置
			useDefaultSalaryItems() {
				this.salaryItems = [{
						itemId: "1",
						itemName: "基本工资",
						itemType: 1,
						fieldName: 'salaryItem_1',
						isIncome: true
					},
					{
						itemId: "2",
						itemName: "绩效奖金",
						itemType: 1,
						fieldName: 'salaryItem_2',
						isIncome: true
					},
					{
						itemId: "4",
						itemName: "养老保险（个人）",
						itemType: 2,
						fieldName: 'salaryItem_4',
						isIncome: false
					},
					{
						itemId: "5",
						itemName: "医疗保险（个人）",
						itemType: 2,
						fieldName: 'salaryItem_5',
						isIncome: false
					},
					{
						itemId: "1990994050818953218",
						itemName: "失业保险（个人）",
						itemType: 2,
						fieldName: 'salaryItem_1990994050818953218',
						isIncome: false
					},
					{
						itemId: "7",
						itemName: "住房公积金（个人）",
						itemType: 2,
						fieldName: 'salaryItem_7',
						isIncome: false
					},
					{
						itemId: "8",
						itemName: "个人所得税",
						itemType: 2,
						fieldName: 'salaryItem_8',
						isIncome: false
					}
				];

				// 构建映射关系
				this.salaryItems.forEach(item => {
					this.salaryItemMap[item.itemId] = {
						fieldName: item.fieldName,
						isIncome: item.isIncome
					};
				});
			},

			// 加载统计数据
			async loadStatisticsData() {
				this.isLoading = true;

				try {
					const queryYear = parseInt(this.selectedYear);
					const queryMonth = this.selectedMonthIndex + 1;

					// 获取该年月的所有工资汇总数据
					const summaryRes = await this.http.get('/VipSalarySummary/list', {
						params: {
							companyId: this.companyId,
							year: queryYear,
							month: queryMonth,
							pageSize: 1000
						}
					});

					// 获取所有员工数据（用于统计在职/离职人数）
					const empRes = await this.http.get('/VipEmployee/list', {
						params: {
							companyId: this.companyId,
							pageSize: 1000
						}
					});

					// 处理员工数据（关键修改：按isOnJob字段判断在职状态）
					this.handleEmployeeData(empRes.data?.data || []);

					// 处理工资汇总数据
					if (summaryRes.code === 200 && summaryRes.data?.data) {
						this.calculateStatistics(summaryRes.data.data, queryYear, queryMonth);
					} else {
						// 没有数据时初始化统计值
						this.resetStatistics();
					}
				} catch (error) {
					console.error('加载统计数据失败:', error);
					this.resetStatistics();
					uni.showToast({
						title: '加载数据失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			},

			// 处理员工数据（关键修改：使用isOnJob字段判断）
			handleEmployeeData(employees) {
				// 统计在职人数（isOnJob=1）
				this.activeEmployeeCount = employees.filter(emp => emp.isOnJob === 1).length;
				// 统计离职人数（isOnJob=0）
				this.inactiveEmployeeCount = employees.filter(emp => emp.isOnJob === 0).length;
				// 总员工数
				this.totalEmployeeCount = this.activeEmployeeCount + this.inactiveEmployeeCount;
			},

			// 计算统计数据
			async calculateStatistics(summaries, year, month) {
				// 初始化统计值
				this.totalPayableSalary = 0;
				this.totalIncomeTax = 0;
				this.totalSocialSecurity = 0;
				this.totalMedicalInsurance = 0;
				this.totalHousingFund = 0;

				// 累加所有汇总数据的应发工资
				this.totalPayableSalary = summaries.reduce((sum, item) => sum + (item.totalIncome || 0), 0);

				// 获取所有工资明细数据以计算各项扣除
				for (const summary of summaries) {
					const detailRes = await this.http.get('/VipSalaryItemDetail/list', {
						params: {
							salarySummaryId: summary.id,
							companyId: this.companyId
						}
					});

					if (detailRes.code === 200 && detailRes.data?.data) {
						this.calculateDeductions(detailRes.data.data);
					}
				}
			},

			// 计算各项扣除的总和
			calculateDeductions(details) {
				// 创建明细映射
				const detailMap = {};
				details.forEach(detail => {
					detailMap[detail.itemId] = detail.itemValue || 0;
				});

				// 累加各项扣除
				// 社保总额 = 养老 + 医疗 + 失业
				this.totalSocialSecurity += (detailMap[this.deductionItemIds.pension] || 0) +
					(detailMap[this.deductionItemIds.medical] || 0) +
					(detailMap[this.deductionItemIds.unemployment] || 0);

				// 医保单独统计（即医疗保险）
				this.totalMedicalInsurance += detailMap[this.deductionItemIds.medical] || 0;

				// 公积金
				this.totalHousingFund += detailMap[this.deductionItemIds.housingFund] || 0;

				// 个人所得税
				this.totalIncomeTax += detailMap[this.deductionItemIds.incomeTax] || 0;
			},

			// 重置统计数据
			resetStatistics() {
				this.totalPayableSalary = 0;
				this.totalIncomeTax = 0;
				this.totalSocialSecurity = 0;
				this.totalMedicalInsurance = 0;
				this.totalHousingFund = 0;
			},

			// 跳转员工管理
			gotoEmployeeManage() {
				// 传递当前选中的年月到员工工资管理页面
				uni.navigateTo({
					url: `/pageNew/salary/salarymangent?year=${this.selectedYear}&month=${this.selectedMonthIndex + 1}`
				});
			}
		}
	};
</script>

<style scoped>
	.page-container {
		min-height: 100vh;
		background: rgba(245, 249, 252, 1);
		padding-bottom: 20px;
	}

	.navbar-left .nav-back-content {
		display: flex;
		align-items: center;
	}

	.navbar-left .nav-title {
		color: #1e88e5;
		font-size: 17px;
		margin-left: 5px;
	}

	.year-picker-container {
		display: flex;
		justify-content: center;
		padding: 15px 0 10px;
		background-color: #f5f7fa;
	}

	.year-picker {
		width: auto;
	}

	.year-display {
		padding: 6px 18px;
		font-size: 16px;
		color: #ffffff;
		border-radius: 4px;
	}

	.selected {
		background-color: #409eff;
	}

	.month-slider {
		width: 100%;
		white-space: nowrap;
		padding-bottom: 15rpx;
		background-color: #f5f7fa;
	}

	.month-tab {
		width: 140rpx;
		height: 60rpx;
		line-height: 60rpx;
		display: inline-block;
		text-align: center;
		margin: 0 10rpx;
		background: rgba(222, 235, 255, 1);
		color: #409eff;
		font-size: 15px;
		border-radius: 10rpx;
	}

	.month-tab-selected {
		background-color: #ffffff;
		color: #409eff;
		border: 2px solid #409eff;
		font-weight: 500;
	}

	.stat-card {
		background-color: #ffffff;
		border-radius: 8px;
		padding: 20px 16px;
		margin: 0 16px 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		position: relative;
	}

	.stat-item {
		margin-bottom: 18px;
	}

	.stat-item:last-child {
		margin-bottom: 0;
	}

	.stat-label {
		font-size: 16px;
		color: #409eff;
		display: inline-block;
		width: 90px;
	}

	.stat-value {
		font-size: 18px;
		color: #333333;
		font-weight: 500;
	}

	.staff-status-container {
		margin-top: 8px;
		margin-left: 90px;
		display: flex;
		gap: 10px;
	}

	.staff-status {
		padding: 3px 10px;
		background-color: #e6f7ff;
		color: #409eff;
		border-radius: 12px;
		font-size: 13px;
	}

	.staff-status-gray {
		background-color: #f5f5f5;
		color: #8c8c8c;
	}

	.employee-manage-btn {
		position: absolute;
		top: 20px;
		right: 16px;
		background-color: #409eff;
		color: #ffffff;
		border-radius: 4px;
		padding: 8px 16px;
		font-size: 15px;
		border: none;
	}

	.config-buttons {
		display: flex;
		justify-content: flex-end;
		gap: 15px;
		padding: 0 16px;
		margin-bottom: 20px;
	}

	.config-btn {
		background-color: #ffffff;
		border: 1px solid #409eff;
		color: #409eff;
		border-radius: 4px;
		padding: 8px 20px;
		font-size: 14px;
		white-space: nowrap;
	}

	.active-btn {
		background-color: #e6f7ff;
	}

	.insure-container {
		display: flex;
		gap: 12px;
		padding: 0 16px;
	}

	.insure-item {
		flex: 1;
		background-color: #ffffff;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	}

	.insure-title {
		display: block;
		background-color: #409eff;
		color: #ffffff;
		text-align: center;
		padding: 12px;
		font-size: 16px;
	}

	.insure-value {
		display: block;
		text-align: center;
		padding: 15px 0;
		font-size: 18px;
		color: #333333;
		font-weight: 500;
	}

	/* 加载状态样式 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 50px 0;
	}

	.loading-text {
		margin-top: 20rpx;
		font-size: 16px;
		color: #666;
	}
</style>